program Project2;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  arr: array of integer;
  i, N, M, r : integer;

procedure Heapify(num: integer);
var
  x, a, b: integer;
begin
  while (1=1) do
  begin
    x := arr[num];
    a := 2000000000;
    b := 2000000000;
    if (2*num+1 < N) then
      a := arr[2*num+1];
    if (2*num+2 < N) then
      b := arr[2*num+2];
    if (a <= b) and (a<x) then
    begin
      arr[num] := a;
      arr[2*num+1] := x;
      num:=2*num+1
    end else if (b <= a) and (b < x) then
    begin
      arr[num] := b;
      arr[2*num+2] := x;
      num := 2*num+2;
    end else
    break;
  end;
end;

begin
  randomize;
  N:=10;
  setlength(arr, N);
  for i := 0 to N-1 do
    arr[i] := random(10);
  for i := 0 to N-1 do
    write(arr[i]);
  writeln;
  for i := N-1 downto 0 do
    Heapify(i);
  M := N;
  for i := 0 to M-1 do
  begin
    r := arr[0];
    arr[0] := arr[n-1];
    arr[n-1] := r;
    dec(N);
    Heapify(0);
  end;
  N:=M;
  for i := 0 to N-1 do
    write(arr[i]);
  readln;
end.
